package com.example.demo.controller;

import com.example.demo.request.LoginRequest;
import com.example.demo.response.ApiResponse;
import com.example.demo.response.LoginResponse;
import com.example.demo.service.UserService;
import com.example.demo.exception.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping
    public ResponseEntity<ApiResponse<LoginResponse>> login(
            @Valid @RequestBody LoginRequest request,
            HttpServletRequest requestObj) {

        LoginResponse loginResponse = userService.login(request);

        // 权限检查
        if (!loginResponse.isHasPermission()) {
            throw new NoPermissionException("没有登录权限");
        }

        // 登录成功
        return ResponseEntity.ok(
                ApiResponse.success(loginResponse, "登录成功", requestObj.getRequestURI(), null)
        );
    }
}
